package com.axe.processdatasync;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyContentProvider extends ContentProvider {


    private String TAG = "MyContentProvider";


    @Override
    public boolean onCreate() {
        Log.i(TAG, "enter oncreate:"+android.os.Process.myPid());
        return true;
    }

    @Nullable
    @Override
    public Bundle call(@NonNull String method, @Nullable String arg, @Nullable Bundle extras) {

        Log.i(TAG, "enter call");

        User user = AuthInfo.getInstance().getUser();

        Bundle bundle = new Bundle();

        JSONObject jsonObject = new JSONObject();
        if (user == null) {
            try {
                jsonObject.put("isAuth",false);
                bundle.putString("data",jsonObject.toString());
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            return bundle;
        } else {
            try {
                jsonObject.put("name", user.getName());
                jsonObject.put("gender", user.getGender());
                jsonObject.put("age", user.getAge());
                jsonObject.put("description", user.getDescription());
                jsonObject.put("isAuth",AuthInfo.getInstance().isAuth());

                JSONArray jsonArray = new JSONArray();
                for (String hobby : user.getHobbys()) {
                    jsonArray.put(hobby);
                }
                jsonObject.put("hobbys", jsonArray);

                bundle.putString("data",jsonObject.toString());

            } catch (Exception e) {
                Log.e("MainActivity", e.getLocalizedMessage());
            }
            return bundle;
        }


    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
        return null;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        return null;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }
}
